package com.demo.youxuanmall.controller;

import com.demo.youxuanmall.service.SystemSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

/**
 * 自定义错误控制器
 * 用于处理所有Spring Boot默认错误
 */
@Slf4j
@Controller
public class CustomErrorController extends BaseController implements ErrorController {

    public CustomErrorController(SystemSettingService systemSettingService) {
        super(systemSettingService);
    }

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        
        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());
            
            if (statusCode == HttpStatus.NOT_FOUND.value()) {
                log.error("404 错误：{}", request.getRequestURI());
                return "error/404";
            } else if (statusCode == HttpStatus.FORBIDDEN.value()) {
                log.error("403 错误：{}", request.getRequestURI());
                return "error/403";
            } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                log.error("500 错误：{}", request.getRequestURI());
                return "error/500";
            }
        }
        
        log.error("未知错误：{}", request.getRequestURI());
        return "error/error";
    }

    @RequestMapping("/403")
    public String accessDenied() {
        return "error/403";
    }

    @RequestMapping("/404")
    public String notFound() {
        return "error/404";
    }

    @RequestMapping("/500")
    public String serverError() {
        return "error/500";
    }
} 